<?php 
namespace app\company\controller;

use app\company\service\DataService;
use library\Controller;
use think\Db;
use think\facade\Config;
/**工具类**/
use app\wechat\controller\WechatTool;
use think\facade\Log;
use think\Validate;
use \Yunpian\Sdk\YunpianClient;
use redis\Redis;
/**
 * 公司管理
 * Class User
 * @package app\worker\controller
 */
class Company extends Controller
{
    /**
     * 绑定当前数据表
     * @var string
     */
    protected $table = 'company';
    protected $table1 = 'CompanyUserDepartment';
    protected $view_table = 'view_company';
    //private static  $wx_config = \think\facade\Config::load(\think\facade\Env::get('root_path').'application/api/config/wxPay.php');
    /**
     * 企业管理
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    { 
        $dbconf = $this->getconfig('vister_db');
        $where ='';
        $uinfo = $this->getGuserinfo();

        if($uinfo['db1']['authorize']!=1 && $uinfo['db1']['authorize']!=0){
            $check = $uinfo['db2']['companyid']==NULL?:'';
            if(!$check){
                 $where = 'companyid = '.$uinfo['db2']['companyid'];
            }         
           
        }

         $this->title = '企业管理';
         $create_at_first=trim($this->request->param('create_at_first'))?strtotime($this->request->param('create_at_first')):'';
         $create_at_last=trim($this->request->param('create_at_last'))?strtotime($this->request->param('create_at_last'))+3600*24:'';

                     if(!$create_at_first||!$create_at_last){

                          $this->_query(Db::connect($dbconf)->table($this->view_table))->where($where)->like('name,code,corporation')->equal('status')->where('deleteTime is null')->order('createtime desc')->page();
                                        
                        }
                        else{
                          $this->_query(Db::connect($dbconf)->table($this->view_table))->where($where)
                                                                                        ->like('name,code,corporation')
                                                                                        ->equal('status')
                                                                                        ->where('deleteTime is null')
                                                                                        ->where('createtime','between',[$create_at_first,$create_at_last])
                                                                                        ->order('createtime desc')
                                                                                        ->page();
                    }
    }
    /**
     * 公司申请加入审核表
     * @auth         true
     * @throws         hink\Exception
     * @throws         hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-10T10:23:59+0800
     * @LastTime     2020-11-10T10:23:59+0800
     * @return       [type]                       [description]
     */
    public function indxcompanyuserreview(){
      $this->title = '员工申请加入审核';
      $dbconf = $this->getconfig('vister_db');
      $userinfo =  $this->getGuserinfo();
      $where = '';
      if($userinfo['db2']!=NULL){
        if(!$userinfo['db2']['companyid']){$this->error('参数错误');}
        $where = 'apply_companyid = '.$userinfo['db2']['companyid'];
      }
      
      $create_at_first=trim($this->request->param('create_at_first'))?strtotime($this->request->param('create_at_first')):'';
      $create_at_last=trim($this->request->param('create_at_last'))?strtotime($this->request->param('create_at_last'))+3600*24:'';


      if($this->request->param('dept_id')){
        if($where){
            $where = $where.' and apply_deptid = '.$this->request->param('dept_id');
        }else{
            $where = 'apply_deptid = '.$this->request->param('dept_id');
        }
        $this->assign('dep_id',$this->request->param('dept_id'));
      }

      if(!$create_at_first||!$create_at_last){

           $this->_query(Db::connect($dbconf)->table('view_apply'))->where($where)->like('user_name,user_mobile,company_name')->equal('apply_status')->where('apply_deletetime is null')->order('apply_createtime desc')->page();            
         }
         else{
           $this->_query(Db::connect($dbconf)->table('view_apply'))->where($where)
                                                                   ->like('user_name,user_mobile,company_name')
                                                                   ->equal('apply_status')
                                                                   ->where('apply_deletetime is null')
                                                                   ->where('apply_createtime','between',[$create_at_first,$create_at_last])
                                                                   ->order('apply_createtime desc')
                                                                   ->page();
              }

    }
    /**
     * 公司信息(公司认证)
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-13T14:11:59+0800
     * @LastTime     2020-11-13T14:11:59+0800
     * @return       [type]                       [description]
     */
    public function companycenter(){
        $this->title = '公司认证';
        $userinfo = $this->getGuserinfo();
        $dbconf = $this->getconfig('vister_db');
        $fetch_data = [];


        if($userinfo['db1']['authorize'] ==2 || $userinfo['db1']['authorize'] ==8){
           $where = 'id = '.$userinfo['db2']['companyid'];
           $fetch_data['companyinfo'] =  Db::connect($dbconf)->table('view_company')->where($where)->find();
           $where = 'companyid = '.$userinfo['db2']['companyid'];
           $fetch_data['storememberinfo'] = Db::connect($dbconf)->table('view_company_store_member')->where($where)->find();

        }else{

            $fetch_data['companyinfo'] =[
                'id'=>0,
                'status'=>0,
                'imgurl'=>NULL,
                'warrant'=>NULL,
            ];
            $fetch_data['storememberinfo'] =[];
            //超级管理员
            if($userinfo['db1']['authorize'] == 1){
                $where = 'id = 9999';
                $fetch_data['companyinfo'] =  Db::connect($dbconf)->table('view_company')->where($where)->find();
                $fetch_data['storememberinfo'] = [];
            }

            if($userinfo['db1']['authorize'] == 9){
                $check_user_company =  Db::connect($dbconf)->table('view_company')->where('createuid = '.$userinfo['db2']['id'])->find();
                if($check_user_company){
                    $where = 'id = '.$check_user_company['id'];
                    $fetch_data['companyinfo'] =  Db::connect($dbconf)->table('view_company')->where($where)->find();
                    $fetch_data['storememberinfo'] = [];
                }

            }
        }

        $where = 'id = '.$userinfo['db1']['authorize'];
        $fetch_data['authorizeinfo'] = Db::table('system_auth')->where($where)->find(); 


        //var_dump($fetch_data);
        if($this->request->param('type')=='update'){
            if($fetch_data['companyinfo']['status']==0){ $this->fetch('companycenterstatic',$fetch_data);}
            $this->fetch('',$fetch_data);
        }

        if($fetch_data['companyinfo']['status']==2){
           $this->fetch('companycenterstatic',$fetch_data);
        }

        if($fetch_data['companyinfo']['status']==0){
            $this->fetch('',$fetch_data);
            
        }
         $this->fetch('',$fetch_data);
    }
    public function ajaxcompanycenter(){

        $userinfo = $this->getGuserinfo();
        $dbconf = $this->getconfig('vister_db');
        $fetch_data = [];

        if($userinfo['db1']['authorize'] ==2 || $userinfo['db1']['authorize'] ==8){
           $where = 'id = '.$userinfo['db2']['companyid'];
           $fetch_data['companyinfo'] =  Db::connect($dbconf)->table('view_company')->where($where)->find();
           $where = 'companyid = '.$userinfo['db2']['companyid'];
           $fetch_data['storememberinfo'] = Db::connect($dbconf)->table('view_company_store_member')->where($where)->find();

        }else{

            $fetch_data['companyinfo'] =[
                'id'=>0,
                'status'=>0,
                'imgurl'=>NULL,
                'warrant'=>NULL,
            ];
            $fetch_data['storememberinfo'] =[];
            //超级管理员
            if($userinfo['db1']['authorize'] == 1){
                $where = 'id = 9999';
                $fetch_data['companyinfo'] =  Db::connect($dbconf)->table('view_company')->where($where)->find();
                $fetch_data['storememberinfo'] = [];
            }

            if($userinfo['db1']['authorize'] == 9){
                $check_user_company =  Db::connect($dbconf)->table('view_company')->where('createuid = '.$userinfo['db2']['id'])->find();
                if($check_user_company){
                    $where = 'id = '.$check_user_company['id'];
                    $fetch_data['companyinfo'] =  Db::connect($dbconf)->table('view_company')->where($where)->find();
                    $fetch_data['storememberinfo'] = [];
                }

            }
        }

        $where = 'id = '.$userinfo['db1']['authorize'];
        $fetch_data['authorizeinfo'] = Db::table('system_auth')->where($where)->find(); 
        $fetch_data['userinfo'] = $userinfo;
        $this->success('请求成功',$fetch_data,200);

    }

    /**
     * 同步功能(弃用)
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-09-11T15:23:54+0800
     * @LastTime     2020-09-11T15:23:54+0800
     * @return       [type]                       [description]
     */
    public function sync(){
        $dbconf = $this->getconfig('vister_db');
        $res = Db::connect($dbconf)->table('view_company')->select();
        $countinsert = 0;

        foreach ($res as $key => $value) {
            # code...
            $check = Db::table('company')->where('code',$value['code'])->find();
            if($check==NULL){
                $data = [
                    'id' => $value['id'],
                    'name' => $value['name'],
                    'code' => $value['code'],
                    'corporation' => $value['corporation'],
                    'address' => $value['address'],
                    'imgurl' => $value['imgurl'],
                    'score' => $value['score'],
                    'expiretime' => $value['expiretime'],
                    'createuid' => $value['createuid'],
                    'createtime' => $value['createtime'],
                    'status' => $value['status'],
                ];
                // if($value['name']!=NULL){
                $result = Db::name('company')->insert($data);
                $countinsert++;
                echo '<div style="text-align: center;">成功同步-'.$value['name'].'</div></br>';
                // }

            }else{
                /*update*/
            }

        }

        echo '<div style="text-align: center;">同步完成--一共同步:'.$countinsert.'家企业</div>';


    }
    /**
     * 获取公司列表
     */
    public function getlist(){
        $dbconf = $this->getconfig('vister_db');
        $name = $this->request->param('name');
        $where = '';
        if($name){
          $where = 'name like "%'.$name.'%"';
        }
        
        $res = Db::connect($dbconf)->table('view_company')->where($where)->select();
        return toJson(['code'=>200,'data'=>$res]);

    }
    /**
     * 获取公司受访人(API)
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function getappuserlist(){
        $companyid = $this->request->param('companyid');
        if(empty($companyid)){return toJson(['code'=>400]);}
        $dbconf = $this->getconfig('vister_db');
        $where = 'Interviewees = 1 and companyid = '.$companyid;
        $res = Db::connect($dbconf)->table('view_user')->where($where)->select();
        return toJson(['code'=>200,'data'=>$res]);
    }
    public function getdeptlist(){
        $deptid =  $this->request->param('deptid');
        $companyid = $this->request->param('companyid');
        $dbconf = $this->getconfig('vister_db');
        $where =  'companyid = '.$companyid;
        $res = Db::connect($dbconf)->table('dept')->where($where)->select();
        return toJson(['code'=>200,'data'=>$res]);
    }

    /**
     * 添加企业
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {

        $dbconf = $this->getconfig('vister_db');
        //var_dump($this->request->param(''));
        //exit();
        $ulist = Db::connect($dbconf)->table('view_user')->select();
        $property_company = Db::connect($dbconf)->table('view_company')->where('type = 2')->select();
        //var_dump($userlist);
        $this->assign('data',[
          'userlist' => $ulist,
          'propertylist' => $property_company,
        ]);
        $this->assign('vo',['id'=>0,'imgurl'=>'']);


        if($this->request->isPost()){

            $upswitch = $this->request->param('upye_switch')=='on'?'on':'off';
            //var_dump($this->request->param('upye_switch'));
            if($upswitch=='on'){
              $imgurl = $this->request->param('uploadyyzz')?:'';
              try{

                $ai = new \Baidu_AI();
                $res = $ai->business_license_verify($imgurl);
              }catch(\Throwable $th){

                $this->error('请检查营业执照是否正确');
              }
              // $name = $res['words_result']['单位名称']['words'];
              // $code = $res['words_result']['社会信用代码']['words'];                
              // $corporation = $res['words_result']['法人']['words'];                
              // $address = $res['words_result']['地址']['words']; 
  
              // if( $name == '无' && $code == '无' && $corporation == '无'&& $address == '无' ){
              //     $this->error('营业执照验证失败');            
              // }
              // $companyname = $this->request->param('name')!=$name?$name:$name;
            }else{

              $imgurl = $this->request->param('uploadyyzz')?:'';
            }
            $companyname = $this->request->param('name');
            $code = $this->request->param('code');
            $corporation = $this->request->param('corporation')?:'';
            $address = $this->request->param('address'); 
            $validate = Validate::make([
                'name' => 'require',
                'code' => 'require',
                'corporation' => 'require',
                'address' => 'require',
            ]);
            
            $data = [
                'name'  => $companyname,
                'code' => $code,
                'corporation' => $corporation,
                'address' => $address,
            ];
            if (!$validate->check($data)) {
                $this->error('用户信息丢失');
            }

            //重复公司
            $check_replace =  Db::connect($dbconf)->table($this->view_table)->where('code like "%'.$code.'%"')->find();
            if($check_replace){$this->error("公司{$companyname}-{$code}已存在,请勿重复添加");}
            $data = [
                'name' => $companyname,
                'imgurl' => $imgurl,
                'createuid' => $this->request->param('createuid')?:0,
                'code' => $code,
                'corporation' => $corporation,
                'address' => $address,
                'createtime' => time(),
                'type' => $this->request->param('type'),

            ];
            $res = Db::connect($dbconf)->table($this->table)->insertGetId($data);
            //插入关系
            if($res==0){$this->error('新增公司失败,参数错误');}
            $relation_data = [
              'incompany_id' => $res,
              'createtime' => time(),
            ];
            switch ($data['type']) {
              case '1':
                # code...
                $relation_data['property_id'] = $this->request->param('property_id');
                break;
              case '2':
              case '3':
                # code...
                //必须公司表9999为最上层本公司
                $relation_data['property_id'] = 9999;
                break;
              default:
                $relation_data['property_id'] = 9999;
                # code...
                break;
            }

            $res_relation = Db::connect($dbconf)->table('property_relation')->insert($relation_data);

           

            $this->success('成功添加企业','');
           
        }

        $this->_form(Db::connect($dbconf)->table($this->table), 'form');
    }

    protected function _form_page_filter(&$userlist){
        
    
        
  //  精准回调对 $data 进行二次处理，注意是引用
    }
    
    
    /**
     * 修改企业
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {

        $dbconf = $this->getconfig('vister_db');
        $id = $this->request->param('id');
        $userinfo = $this->getGuserinfo();
        /**受访人列表**/
        $where = $userinfo['db1']['authorize']!='1'?'Interviewees = 1 and companyid = '.$id:'1=1';
        $Interviewees_info = Db::connect($dbconf)->table('view_user')->where($where)->select();
        if($userinfo['db1']['authorize']==1){
          $ulist = Db::connect($dbconf)->table('view_user')->select();
        }else{
          $ulist = Db::connect($dbconf)->table('view_user')->where('companyid = '.$id)->select();
        }
        $property_company = Db::connect($dbconf)->table('view_company')->where('type = 2')->select();

        $member_info = Db::connect($dbconf)->table('view_company_store_member')->where('companyid = '.$id)->find();
        $this->assign('data',[
            /**丢给视图的数据**/
            'userlist'=>$ulist,
            'intervieweesinfo'=>$Interviewees_info,
            'propertylist' => $property_company,
            'member_info' => $member_info,
        ]);

 // array(10) { ["id"]=> string(1) "9" ["spm"]=> string(7) "m-77-78" ["open_type"]=> string(5) "modal" ["name"]=> string(36) "温州佳悦企业管理有限公司" ["select_base_cityname"]=> string(0) "" ["createuid"]=> string(0) "" ["type"]=> string(1) "2" ["old_local_url"]=> string(64) "http://pc.zsicp.com/upload/78001822a73963ad/44be5955d0a44ae7.jpg" ["ye_switch"]=> string(2) "on" ["local_url"]=> string(18) "{{item.local_url}}" }
 
        if($this->request->isPost()){
            // var_dump($this->request->param(''));
            // exit();
            $local_url = $this->request->param('uploadyyzz')=='/static/plugs/uploader/theme/image.png' ||  $this->request->param('uploadyyzz') == '{{item.local_url}}'?'':$this->request->param('uploadyyzz');

            if($local_url==''){$this->error('请检查营业执照是否正确.');}
            if($userinfo['db1']['authorize']!=1){
                $data['status'] = 0; 
            }
            $data['name'] = $this->request->param('name');              
            $data['address'] = $this->request->param('address');
            $data['imgurl'] = $this->request->param('uploadyyzz');
            $data['code'] = $this->request->param('code');
            $data['corporation'] = $this->request->param('corporation')?:'';
            // if(!$data['imgurl']){
            //   $data['imgurl'] = $this->request->param('local_url');
            // }
            // if(!$data['imgurl']){
            //    $data['imgurl'] = $this->request->param('uploadyyzz');
            // }
          // }
            $where = ['id'=>$id];
            $old_compamy_info = Db::connect($dbconf)->table($this->view_table)->where($where)->find();

            $data['createuid'] = $this->request->param('createuid');
            $data['type'] = $this->request->param('type');
            $data['status'] = $data['createuid']==NULL?0:2;
            $where=['id'=>$id];
    
            $res = Db::connect($dbconf)->table($this->table)->where($where)->data($data)->update();

            /**公司关系**/
            $find_property_relation = Db::connect($dbconf)->table('property_relation')->where(['incompany_id'=>$id])->find();
            switch ($data['type']) {
              //有物业管理公司
              case '1':
                if($find_property_relation){
                  $where = 'id = '.$find_property_relation['id'];
                  $data = [
                    'property_id' => $this->request->param('property_id'),
                  ];
                  $res = Db::connect($dbconf)->table('property_relation')->where($where)->data($data)->update();
                }else{

                  $data = [
                    'property_id' => $this->request->param('property_id'),
                    'createtime' => time(),
                    'incompany_id' => $id,
                  ];
                  $res = Db::connect($dbconf)->table('property_relation')->insert($data);
                }
                # code...
                break;
              case '2':
                //物业公司
                //   if($find_property_relation){
                //   $where = 'id = '.$find_property_relation['id'];
                //   $data = [
                //     'property_id' => $this->request->param('property_id'),
                //   ];
                //   $res = Db::connect($dbconf)->table('property_relation')->where($where)->data($data)->update();
                // }else{

                //   $data = [
                //     'property_id' => $this->request->param('property_id'),
                //   ];
                //   $res = Db::connect($dbconf)->table('property_relation')->insert($data);
                // }
                # code...
                // break;
              case '3':
                //无物业公司,普通公司
                if($find_property_relation){
                  $where = 'id = '.$find_property_relation['id'];
                  $data = [
                    'property_id' => 9999,
                  ];
                  $res = Db::connect($dbconf)->table('property_relation')->where($where)->data($data)->update();
                }else{

                  $data = [
                    'property_id' => 9999,
                    'createtime' => time(),
                    'incompany_id' => $id,
                  ];
                  $res = Db::connect($dbconf)->table('property_relation')->insert($data);
                }
                break;
              default:
                $this->error('保存失败,请确认公司类型');
                # code...
                break;
            }
            /**变更接待人**/

            /**变更boss**/
            if($old_compamy_info['createuid']!=$this->request->param('createuid')){
              //var_dump(1);
              $where = ['id'=>$this->request->param('createuid')];
              $data = [
                'roleid' => 2,
                'companyid' => $id,
              ];
              //是否物业类型
              if($old_compamy_info['type'] == 2){$data['roleid'] = 8;}
              //更新dev 用户表
              $res = Db::connect($dbconf)->table('user')->where($where)->data($data)->update();

              $new_compamy_info = Db::connect($dbconf)->table($this->view_table)->where(['id'=>$id])->find();

              try{
                  $data = [
                      'roleid'=>2,
                      'authorize'=>2,
                      'companyid'=>$id,
                    ];
                  if($new_compamy_info['type'] ==2 ){
                    $data['roleid'] = 8;
                    $data['authorize'] = 8;
                  }


                  Db::table('system_user')->where(['openid'=>$new_compamy_info['openid']])->data($data)->update();
              }catch(\Throwable $th){
                    Log::info('更新公司数据失败ID:'.$id.'');
              }

              //恢复旧boos
              $res = Db::connect($dbconf)->table('user')->where(['id'=>$old_compamy_info['createuid']])->data(['roleid'=>0,'companyid'=>NULL])->update();
              try{
                  $res = Db::table('system_user')->where(['openid'=>$old_compamy_info['openid'],'authorize'=>2])->data(['roleid'=>0,'authorize'=>9,'companyid'=>NULL])->update();
              }catch(\Throwable $th){
                    Log::info('更新公司数据失败ID:'.$id.'-恢复旧boos事失败');
              }
              
            }

            $this->success('成功修改信息','');
           
        }
        $this->_form(Db::connect($dbconf)->table($this->view_table), 'form');
    }
    /**
     * 申请加入公司人员详情
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-13T15:23:19+0800
     * @LastTime     2020-11-13T15:23:19+0800
     * @return       [type]                       [description]
     */
    public function details_review(){
        var_dump($this->request->param(''));
        $dbconf = $this->getconfig('vister_db');
        $applyuinfo = Db::connect($dbconf)->table('view_user')->where('id = '.$this->request->param('user_id'))->find();
        $apply_info = Db::connect($dbconf)->table('view_apply')->where('id = '.$this->request->param('id'))->find();
        $data = [
            'apply_uinfo' => $applyuinfo,
            'apply_info' => $apply_info,
        ];
        $this->assign('data',$data);
    }
    /**
     * 详情
     * @auth         true
     * @throws         hink\Exception
     * @throws         hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-02T16:33:26+0800
     * @LastTime     2020-11-02T16:33:26+0800
     * @return       [type]                       [description]
     */
    public function details(){
      return $this->error('无权限访问');
    }
    /**
     * 权限表单数据处理
     * @param array $data 表单数据
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_filter(&$data)
    {
        
        if ($this->request->isGet()) {
            $where = ['status' => '1', 'is_deleted' => '0'];
            $this->auths = Db::name('company_user_auth')->where($where)->order('sort desc,id desc')->select();
            array_unshift($this->auths, ['id' => '0', 'title' => '所有权限', 'path' => '/']);
            $data['svn_authorize'] = isset($data['svn_authorize']) ? explode(',', $data['svn_authorize']) : [];
        } else {
            if (isset($data['svn_authorize']) && is_array($data['svn_authorize'])) {
                $data['svn_authorize'] = join(',', $data['svn_authorize']);
            } else {
                $data['svn_authorize'] = '';
            }
            // $macs = [];
            // foreach (explode(PHP_EOL, preg_replace("/\s+/", PHP_EOL, trim($data['mobile_macs']))) as $mac) {
            //     if (DataService::applyMacValue($mac)) $macs[] = $mac;
            // }
            // $data['mobile_macs'] = join(PHP_EOL, array_unique($macs));
        }
        
        // $this->userlist = Db::name('CompanyUserDepartment')
        //  
        //                 ->order('id desc')
        //                 ->limit(1,1)
        //                 ->value('department');
        // $this->userlist = Db::name('CompanyUserDepartment')->where('status',1)->order('id asc')->column('department');
        if($this->request->param('id')) {
            $dbconf = $this->getconfig('vister_db');
            $where = 'companyid = '.$this->request->param('id');
            $this->userlist = Db::connect($dbconf)->table('view_user')->where($where)->select();
            $where = 'id = '.$this->request->param('id');
            $this->companyname = Db::connect($dbconf)->table('view_company')->where($where)->select();
        }else{
            $this->companyname = [];
            $this->userlist = [];
               
        }
        //var_dump($this->companyname);
    }
    /**
     * 申请加入公司状态审核
     * @auth         true
     * @throws         hink\Exception
     * @throws         hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-10T11:18:21+0800
     * @LastTime     2020-11-10T11:18:21+0800
     * @return       [type]                       [description]
     */
    public function state_review(){
        $dbconf = $this->getconfig('vister_db');
        $status = $this->request->param('status');
        $apply_id = $this->request->param('id');

        if($this->request->isPost()){
            $applyinfo = Db::connect($dbconf)->table('view_apply')->where('id = '.$apply_id.' and apply_status = 0')->find();
            if(!$applyinfo){$this->error('申请已确认');}
            $deptinfo = Db::connect($dbconf)->table('view_company_dept')->where('id = '.$applyinfo['apply_deptid'])->find();

            $updata = [
                'companyid'=>$applyinfo['apply_companyid'],
                'deptid'=>$applyinfo['apply_deptid'],
                'roleid'=>$applyinfo['apply_roleid'],
            ];
            if($deptinfo['is_security']==1){$updata['roleid']=$applyinfo['apply_roleid']?$applyinfo['apply_roleid']:6;}
            //尝试更改pc 用户数据
            try{
                $apply_u_data = Db::connect($dbconf)->table('view_user')->where('id = '.$applyinfo['apply_uid'])->find();
    
                $u_data = [
                    'roleid'=>$applyinfo['apply_roleid'],
                    //慎
                    'authorize'=>$applyinfo['apply_roleid'],
                ];
    
                Db::connect($dbconf)->table('system_user')->where('openid = "'.$apply_u_data['openid'].'"')->data($u_data)->update();
            }catch(\Throwable $th){
                //淦！
            }

            switch ($status) {
                case 1:
                    $res = Db::connect($dbconf)->table('user')->where('id = '.$applyinfo['apply_uid'])->data($updata)->update();
                    //发送审核消息
                    $data = [
                        'openid' => $applyinfo['user_openid'],
                        'url' => 'https://devs.zsicp.com/h5/',
                        'title' => "申请通知",
                        'name' => $applyinfo['user_name'],
                        'mobile' => "恭喜,加入{$deptinfo['name']}-{$deptinfo['dept_name']}",
                        'time' => date("Y-m-d H:i:s",time()),
                        'status' => '审核通过',
                        'remark' => '',
                    ];
                    $sendRes = WechatTool::send_message($data);

                    # code...
                    break;
                case 2:

                    //发送审核消息
                    $data = [
                        'openid' => $applyinfo['user_openid'],
                        'url' => 'https://devs.zsicp.com/h5/',
                        'title' => "申请通知",
                        'name' => $applyinfo['user_name'],
                        'mobile' => "未能加入 {$deptinfo['name']}-{$deptinfo['dept_name']}", //此处是图文标题
                        'time' => date("Y-m-d H:i:s",time()),
                        'status' => '审核不通过',
                        'remark' => '',
                    ];
                    $sendRes = WechatTool::send_message($data);
                    # code...
                    break;
                default:
                    $this->error('无权限操作');
                    # code...
                    break;
            } 
        }


        $data = [
            'status' => $status,
            'deletetime' => time(),
        ];
        $where = [
            'id' =>$apply_id,
        ];
        // if($status==2){
        //     $data['deletetime'] = time();
        // }
        /*修改dev数据库
        waiting
        code............
        */
        $this->_save(Db::connect($dbconf)->table('apply'), $data, $field = '', $where);

    }
    /**
     * 更改企业/审核状态
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function state()
    {

        $status = $this->request->param('status');
        $code = $this->request->param('code');
        $userinfo = $this->getGuserinfo();
        $dbconf = $this->getconfig('vister_db');
        if($status == 2){
            $where = 'code = "'.$code.'" and deleteTime is null';
            /*此处用户id对应到　dev数据库---以下操作仅对dev操作*/
            // $companydata = Db::table('company')->where($where)->find();
            //获取该用户(企业经营者)|公司信息
            $companydata = Db::connect($dbconf)->table('view_company')->where($where)->order('createtime  desc')->find();
            if($companydata['createuid']==0 || $companydata['createuid']==NULL){$this->error('请绑定该公司企业管理者');}
            if($companydata){
              //设置用户权限
              //dev
                $data = [
                    'companyid' => $companydata['id'],
                    'roleid' =>2,
                    'Interviewees' => 1
                ];
                if($companydata['type'] == 2){$data['roleid'] = 8;}
                $where = 'id = '.$companydata['createuid'];
                $res = Db::connect($dbconf)->table('user')->where($where)->data($data)->update();
              //pc
                $roledata = [
                    'roleid' => 2,
                    'authorize' => 2,
                    'companyid' => $companydata['id'],
                ];
                //物业
                if($companydata['type'] == 2){$roledata['roleid'] = 8;$roledata['authorize'] = 8;}
                //可删除-admin
                if($userinfo['db1']['openid']==$companydata['openid']){$roledata['authorize'] = 1;}
                
                $where = 'openid = "'.$companydata['openid'].'"';
                $res = Db::table('system_user')->where($where)->data($roledata)->update();

                //设置公司审核状态
                $where = 'code = "'.$code.'"';
                $data = [
                    'status' => 2,
                    'examinetime' => time(),
                ];
                $res = Db::connect($dbconf)->table('company')->where($where)->data($data)->update();

                //发送审核消息
                $data = [
                    'openid' => $companydata['openid'],
                    'url' => 'https://devs.zsicp.com/h5/',
                    'title' => '审核营业执照',
                    'name' => $companydata['user_name'],
                    'mobile' => $companydata['mobile'],
                    'time' => date("Y-m-d H:i:s",time()),
                    'status' => '审核通过',
                    'remark' => '',
                ];
                $sendRes = WechatTool::send_message($data);

            }

            /*自动新增部门*/
            $where = 'companyid = '.$companydata['id'];
            $countdept =  Db::connect($dbconf)->table('dept')->where($where)->count();
            if($countdept==0){
                $deptarr = ['保安部','行政部','技术部','销售部','生产部'];
                $indeptdata = [
                    'companyid' =>$companydata['id'],
                    'createtime' =>time(),
                ];
                for ($i=0; $i <=4 ; $i++) { 
                    # code...
                    if($i==0){
                        $indeptdata['name'] =$deptarr[$i];
                        $indeptdata['is_security'] = 1;
                    }else{
                        $indeptdata['name']=$deptarr[$i];
                        $indeptdata['is_security'] = 0;
                    }
                    //创建部门
                    $dept_in = Db::connect($dbconf)->table('dept')->insertGetId($indeptdata);
                    //初始化部门排排班
                    //设置部门排班

                    $data =  [
                        'start_time' => '08:00:00',
                        'end_time' => '18:00:00',
                        'deptid' => $dept_in,
                        'createtime' => time(),
                    ];
                    $res  = Db::connect($dbconf)->table('scheduling')->insert($data);

                }
            }

            //创建企业会员
            $check_member = Db::connect($dbconf)->table('view_company_store_member')->where('companyid = '.$companydata['id'])->find();
            if($check_member == NULL){
                $data = [
                    'companyid'=>$companydata['id'],
                    'commodityid'=>0,
                    'vip_level'=>2,
                    'vip_date'=>'2100-12-31',
                    'frequency'=>50,
                    'type'=>2,
                ];
                $res = Db::connect($dbconf)->table('store_member')->insert($data);
            }


            $this->success('审核通过');
        }
        //end 通过
        //
        //start 不通过
        //
        if($status==1){
            $where = 'code = "'.$code.'" and deleteTime is null';
            $companydata = Db::connect($dbconf)->table('view_company')->where($where)->order('createtime  desc')->find();
            if($companydata['createuid']==0 || $companydata['createuid']==NULL){$this->error('请绑定该公司企业管理者');}
            //发送审核消息
            $data = [
                'openid' => $companydata['openid'],
                'url' => 'https://devs.zsicp.com/h5/',
                'title' => '审核营业执照-通知',
                'name' => $companydata['user_name'],
                'mobile' => $companydata['mobile'],
                'time' => date("Y-m-d H:i:s",time()),
                'status' => '审核未通过',
                'remark' => '资料不完善,请补充重新提交审核',
            ];
            $sendRes = WechatTool::send_message($data);
            //$this->success('审核不通过');
        }

        $data = [
            'status' => $this->request->param('status'),
            'examinetime' => $this->request->param('status')==2?time():NULL,

        ];
        $where = [
            'code' =>$code,
        ];
        /*修改dev数据库
        waiting
        code............
        */
        $this->_save(Db::connect($dbconf)->table('company'), $data, $field = '', $where);
    }
    /**
     * 删除申请加入公司记录
     * @auth         true
     * @throws         hink\Exception
     * @throws         hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-10T11:19:38+0800
     * @LastTime     2020-11-10T11:19:38+0800
     * @return       [type]                       [description]
     */
    public function remove_review(){
      $dbconf = $this->getconfig('vister_db');
      if($this->request->isPost()){      
        $id=trim($this->request->param('id'));
        // dump($id);
        $data = Db::connect($dbconf)->table('apply')->where("id in ($id)")->useSoftDelete('deletetime',time())->delete();
        $this->success('删除成功');
      }
    }
    /**
     * 删除企业
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {

        $dbconf = $this->getconfig('vister_db');

        // $this->_delete($this->table);
        if($this->request->isPost()){      
        $id=trim($this->request->param('id'));
        // dump($id);
        $data = Db::connect($dbconf)->table($this->table)->where("id in ($id)")->useSoftDelete('deleteTime',time())->delete();
        /**同时恢复公司下的所有用户 删除公司下的所有部门**/
        $res = Db::connect($dbconf)->table('dept')->where("companyid in ($id)")->delete();

        $updata = [
          'companyid' => 0,
          'deptid' => 0,
          'roleid' => 0,
        ];
        $res=  Db::connect($dbconf)->table('user')->where("companyid in ($id)")->data($updata)->update();

        /**删除该公司所有信息**/
        $res = Db::connect($dbconf)->table('appointment')->where("companyid in ($id)")->useSoftDelete('deleteTime',time())->delete();
        $res = Db::connect($dbconf)->table('meeting')->where("companyid in ($id)")->useSoftDelete('deleteTime',time())->delete();
        $res = Db::connect($dbconf)->table('question')->where("companyid in ($id)")->useSoftDelete('deletetime',time())->delete();
        $res = Db::connect($dbconf)->table('property_relation')->where("incompany_id in ($id)")->useSoftDelete('deletetime',time())->delete();
        //删除公司会员信息
        $res = Db::connect($dbconf)->table('store_member')->where("companyid in ($id)")->useSoftDelete('deletetime',time())->delete();
        //删除后台所有人员
        $need_del_user =  Db::connect($dbconf)->table('view_user')->where("companyid in ($id)")->select();

        $updata = [
          'roleid' => 0,
          'companyid' => 0,
          'authorize' => 9,
          'is_deleted' => 0,
        ];
        $res = Db::table('system_user')->where("companyid in ($id)")->data($updata)->update();

        //可同步公司id后删除以下
        if($need_del_user){
          foreach ($need_del_user as $key => $value) {
            # code...
            Db::table('system_user')->where('openid = "'.$value['openid'].'"')->data($updata)->update();
          }
        }

        if($data){
            $this->success('数据删除成功！');
        }
      }
    }

  /**
     * 扫描获取营业执照信息(仅扫描)
     * @auth         false
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-10-21T15:40:49+0800
     * @LastTime     2020-10-21T15:40:49+0800
     * @return       [type]                       [description]
     * @param [type] $[name] [<description>]                 
     *         local_url       图片地址
     */
    public function upload(){
      $dbconf = $this->getconfig('vister_db');
      $local_url = $this->request->param('local_url');
      $type = $this->request->param('companycardtype');
      $is_update = $this->request->param('type'); //update
      if(!$local_url && $type!="update"){$this->error('未上传营业执照');}

      $ai = new \Baidu_AI();
      $res = $ai->business_license_verify($local_url);

      $name = $res['words_result']['单位名称']['words'];
      $code = $res['words_result']['社会信用代码']['words'];                
      $corporation = $res['words_result']['法人']['words'];                
      $address = $res['words_result']['地址']['words'];   

            

      if( $name !== '无' && $code !== '无' && $corporation !== '无'&& $address !== '无' ){
        
        $data = ['name'=>$name , 'code'=>$code,'corporation'=>$corporation,'address'=>$address];

        /**前置判断条件--公共的 无需添加单一条件 单一条件请从外部二次判断**/
        $check_same = Db::connect($dbconf)->table('view_company')->where('code',$code)->find();
        if($check_same && $is_update!='update'){
          return toJson(['message'=>'企业已存在','code'=>'400']);
        } 
      
          return toJson(['message'=>'营业执照验证成功','code'=>'200','data'=>$data,'src'=>$local_url]);
      }else{

        $data = ['name'=>$name , 'code'=>$code,'corporation'=>$corporation,'address'=>$address];
        
        return toJson(['message'=>'营业执照验证失败','code'=>'400']);
      }


      
    }


  /**
     * 更换公司绑定用户|删除公司(验证)
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-10-21T15:40:49+0800
     * @LastTime     2020-10-21T15:40:49+0800
     * @return       [type]                       [description]
     * @param [type] $[name] [<description>]                 
     *      
     */
    public function verif(){
        $redis = new Redis;
        $id = $this->request->param('companyid');
        $dbconf = $this->getconfig('vister_db');
        $companyinfo = Db::connect($dbconf)->table('view_company')->where('id',$id)->find();
        $code_type = $this->request->param('ty'); //Cuser Cdel
        $this->assign('C_type',$code_type);
        $this->assign('vo',['id'=>$id]);
        if($this->request->isPost()){
            $re_code = $this->request->param('code');
            $true_code = $redis::get('pc_phone_Message_C'.$id.'_company_'.$code_type.'_');
            // if(!$true_code){$this->error('验证失败,请重新发送',[],400);}
            // if($re_code != $true_code){$this->error('验证码错误,请确认验证码',[],400);}
            // $redis::del('pc_phone_Message_C'.$id.'_company_'.$code_type.'_');
            $this->success('验证成功',[],200);
            if($re_code == $true_code){
                $this->success('验证成功',[],200);
            }

        }   


        return $this->fetch();
    }


    /**
     * 更换公司绑定用户|删除公司(发送验证码)
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-27T09:21:30+0800
     * @LastTime     2020-11-27T09:21:30+0800
     * @return       [type]                       [description]
     */
    public function send_code(){
        $redis = new Redis;
        $id = $this->request->param('companyid');
        $dbconf = $this->getconfig('vister_db');
        $py_key = Db::connect($dbconf)->table('sysconfig')->where(['name'=>'Yunpian_Apikey'])->find();
        $companyinfo = Db::connect($dbconf)->table('view_company')->where('id',$id)->find();
        $code_type = $this->request->param('ty'); //Cuser Cdel
        $mobile = '15362912806'; //超级管理员手机号
        //初始化client,apikey作为所有请求的默认值
        $clnt = YunpianClient::create($py_key['val']);
        $code = mt_rand(100000,999999);

        $param = [YunpianClient::MOBILE => $mobile ,YunpianClient::TEXT => "【智服网】您正在进行更改{$companyinfo['name']}-系统管理员操作(如非本人操作,请忽略),您的验证码是".$code];

        $redis_set_Str = $code_type =='Cuser'?'pc_phone_Message_C'.$id.'_company_Cuser_'.$mobile:'pc_phone_Message_C'.$id.'_company_Cdel_'.$mobile;
        try{
            $r = $clnt->sms()->single_send($param);
            if($r->isSucc()){

                $redis::set($redis_set_Str,$code,360);
                //Cookie::set('Cookie_Message_'.$userinfo['db1']['id'] ,$code,1200);
                // var_dump($r->data());
                $this->success('验证码成功发送.',[],200);
                return true;
            }else{
                
                $this->error('验证码发送频繁,请等待一段时间再试.',[],400);
                return false;
            }
        }catch(Exception $e) {
            $this->error('验证码发送失败,请稍后再试.',[],400);
        }


    }


}